<?php

namespace server\base;

require __DIR__ . '/../../../public/index.php';


use server\business\Chat;
use Swoole\WebSocket\Server;

class WS extends Base
{
    private $ws = null;
    private $chat = null;


    public function __construct()
    {
        parent::__construct();
        $this->chat = new Chat();
        $this->ws = new Server("0.0.0.0", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
        $this->ws->set([
            'task_worker_num' => 4,
            'ssl_cert_file' => '/www/server/panel/vhost/cert/chat.fxcyl.cn/fullchain.pem',
            'ssl_key_file' => '/www/server/panel/vhost/cert/chat.fxcyl.cn/privkey.pem',
        ]);
        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('task', [$this, 'onTask']);
        $this->ws->on('finish', [$this, 'onFinish']);
        $this->ws->on('close', [$this, 'onClose']);
        $this->ws->start();
    }

    public function onOpen($ws,$request)
    {
        //      $ws->push($request->fd,"欢迎客户端:{$request -> fd}\n");
        $this ->handle($request->get['token'],$request->get['type'],$ws,$request->fd);
    }

    public function onMessage($ws,$frame)
    {
        $this -> chat ->switchBoard($ws,$frame);

    }

    public function onTask($ws, $task_id, $src_worker_id, $data)
    {
        sleep(10);
        return $data;
    }

    public function onFinish($ws, $task_id, $data)
    {
        var_dump('task_id:' . $task_id);
        var_dump($data);
    }


    public function onClose($ws, $fd)
    {
        echo "客户端：{$fd} 关闭\n";
    }
}

new WS();
